package com.nuanshui.heatedloan.web;

import com.alibaba.fastjson.JSON;
import com.nuanshui.heatedloan.extension.shiro.ShiroDbRealm;
import com.nuanshui.heatedloan.extension.shiro.ShiroDbRealm.ShiroUser;
import com.nuanshui.heatedloan.util.SecurityConstants;
import com.nuanshui.heatedloan.util.dwz.AjaxObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 登陆的控制器
 */
@Controller
@RequestMapping(value = { "/cms/manage/login" })
public class LoginController {

	/**
	 * 返回登录页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String login(final HttpServletRequest request) {
		return "cms/login";
	}

	/**
	 * 登陆超时的处理 处理流程：shiro根据session过期时间重定向到这里->返回301给dwz
	 * x-requested-with=XMLHttpRequest为登陆超时，并返回301
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.GET,RequestMethod.HEAD}, headers = "x-requested-with=XMLHttpRequest")
	@ResponseBody
	public String loginDialog(final HttpServletRequest request) {

		ResponseObject result = new ResponseObject();
		result.setStatus(GlobalErrorCode.UNAUTHORIZED);
		String  str = JSON.toJSONString(result);
		return str;
	}

	/**
	 * 登陆超时后打开登录的模态窗口
	 */
	@RequestMapping(value = "/timeout", method = { RequestMethod.GET })
	public String timeout() {
		return "cms/index/loginDialog";
	}

	/**
	 * ajax登陆成功处理
	 */
	@RequestMapping(value = "/timeout/success", method = { RequestMethod.POST })
	@ResponseBody
	public String timeoutSuccess(final HttpServletRequest request) {
		final Subject subject = SecurityUtils.getSubject();
		final ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject
				.getPrincipal();
		// 这个是放入user还是shiroUser呢？
		request.getSession().setAttribute(SecurityConstants.LOGIN_USER,
				shiroUser.getUser());
		final AjaxObject ajaxObject = new AjaxObject("登录成功。");
		ajaxObject.setCallbackType(AjaxObject.CALLBACK_TYPE_CLOSE_CURRENT);

		return ajaxObject.toString();
	}

	/**
	 * 非ajax登陆失败处理
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String fail(
			@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) final String username,
			final Map<String, Object> map, final HttpServletRequest request) {
		final String msg = parseException(request);
		map.put("msg", msg);
		map.put("username", username);
		return "cms/login";
	}

	/**
	 * ajax登陆失败处理
	 */
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.HEAD }, headers = "x-requested-with=XMLHttpRequest")
	@ResponseBody
	public String failDialog(final HttpServletRequest request) {
		final String msg = parseException(request);
		final AjaxObject ajaxObject = new AjaxObject(msg);
		ajaxObject.setErrorCode(AjaxObject.STATUS_CODE_FAILURE);
		ajaxObject.setCallbackType("");
		return ajaxObject.toString();
	}

	/**
	 * 登陆失败的异常
	 * 
	 * @param request
	 * @return
	 */
	private String parseException(final HttpServletRequest request) {
		final String error = (String) request
				.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String msg = "其他错误！";
		if (error != null) {
			if ("org.apache.shiro.authc.UnknownAccountException".equals(error)) {
				msg = "未知帐号错误！";
			} else if ("org.apache.shiro.authc.IncorrectCredentialsException"
					.equals(error)) {
				msg = "密码错误！";
			} else if ("com.nuanshui.heatedloan.extension.shiro.IncorrectCaptchaException"
					.equals(error)) {
				msg = "验证码错误！";
			} else if ("org.apache.shiro.authc.AuthenticationException"
					.equals(error)) {
				msg = "认证失败！";
			} else if ("org.apache.shiro.authc.DisabledAccountException"
					.equals(error)) {
				msg = "账号被冻结！";
			}
		}
		return "登录失败，" + msg;
	}
}
